<?php
require('../../lib/base.php');
$base=new base(array('web','advertiser'));
$date=((((int)((time()+28800)/86400))*86400)-28800);
$payment=$base->model('payment');
$C=$payment->GPayment(array('select'=>'count(*) AS C','where'=>array('date='=>$date)));
$C=reset($C);$C=$C['C'];
if($C==0){
	$config=$base->model('config');
	$temp=$config->GConfig(array('where'=>array('label ='=>'finance')));
	foreach($temp as $value){$finance[$value['name']]=intval($value['value']);}
	$information=$base->model('information');
	$valid=$information->GMation(array('select'=>'member,money','where'=>array('money>='=>$finance['min'])));
	if(!empty($valid)){
		$bank=$base->model('bank');
		$target=$bank->GBank(array('where'=>array('member IN'=>array_keys($valid),'locked='=>0)));
		$insert=array();$auto=array();$log=array();$date_s=date('Y-m-d',$date);
		foreach($target as $key=>$value){
			$temp=intval($valid[$value['member']]['money']/$finance['min']);
			$auto[$temp][]=$value['member'];$deduction=$temp*$finance['min'];
			if($finance['cess']===1&&$value['type']==0){//劳务个人所得税,个人账户.
				if($tax<=800){$tax=0;}elseif($tax<=4000){$tax=($deduction-800)*0.2;}
				elseif($tax<=20000){$tax=$deduction*0.8*0.2;}
				elseif($tax<=50000){$tax=$deduction*0.8*0.3-2000;}
				else{$tax=$deduction*0.8*0.4-7000;}
			}else{$tax=0;}
			$outlay=$finance['outlay'];$fact=$deduction-$tax-$outlay;
			$insert[]=array($value['member'],$date,$value['type'],$value['company'],$value['province'],$value['city'],$value['subbranch'],$value['account'],$value['name'],$deduction,$tax,$outlay,$fact,$finance['auto']);
			$log[]=array($value['member'],'payment.detail',$base->runtime,'0.0.0.0',serialize(array('money'=>-$deduction,'balance'=>($valid[$value['member']]['money']-$deduction),'remark'=>($date_s.',系统结算'))));
		}
		if(!empty($insert)&&!empty($auto)&&!empty($log)){
			$mysql=$base->library('mysql');
			$mysql->startTrans();$check=true;
			$base->model('log')->ILog(array('field'=>array('member','label','date','ip','content'),'value'=>$log));
			foreach($auto as $key=>$value){
				$set=array('money=money-'=>$key*$finance['min']);
				if($finance['auto']!=0){$set['frozen=frozen+']=$key*$finance['min'];}
				$affected=$information->UMation(array('set'=>$set,'where'=>array('member IN'=>$value)));
				if($affected!=count($value)){
					$mysql->rollback();
					$check=false;break;
				}
			}
			if($check){
				$affected=$payment->IPayment(array('field'=>array('member','date','type','company','province','city','subbranch','account','name','deduction','tax','outlay','fact','locked'),'value'=>$insert));
				if($affected==count($insert)){
					$mysql->commit();
				}else{
					$mysql->rollback();
				}
			}
		}
	}
}
?>